using System;
using System.Web;
using System.IO;
using WindowsLive;

/// <summary>
/// This page handles the 'delauth' Delegated Authentication action.
/// When you create a Windows Live application, you must specify the URL 
/// of this handler page.
/// </summary>
public partial class HandlerPage : System.Web.UI.Page
{
    const string MainPage = "ContactsPage.aspx";
    //const string AuthCookie = "ConsentToken";
    const string AuthCookie = "delauthtoken";
    static DateTime ExpireCookie = DateTime.Now.AddYears(-10);
    static DateTime PersistCookie = DateTime.Now.AddYears(10);

    // Initialize the WindowsLiveLogin module.
    static WindowsLiveLogin wll = new WindowsLiveLogin(true);

    protected void Page_Load(object sender, EventArgs e)
    {
        HttpRequest req = HttpContext.Current.Request;
        HttpResponse res = HttpContext.Current.Response;

        // Extract the 'action' parameter, if any, from the request.
        string action = req["action"];

        if (action == "delauth")
        {
            //Attempt to extract the consent token from the response.
            WindowsLiveLogin.ConsentToken token = wll.ProcessConsent(req.Form);
            
            HttpCookie authCookie = new HttpCookie(AuthCookie);
            // If a consent token is found, store it in the cookie and then 
            // redirect to the main page.
            if (token != null)
            {
                Session["ConsentToken"] = token;
                authCookie.Value = token.Token;
                authCookie.Expires = PersistCookie;
            } 
            else
            {
                authCookie.Expires = ExpireCookie;
            }

            res.Cookies.Add(authCookie);
            res.Redirect(MainPage);
            res.End();
        }
        else
        {
            res.Redirect(MainPage);
            res.End();
        }
    }
}
